

import 'dart:io';

import 'package:dio/dio.dart';

import '../Settings.dart';
import 'DioInterceptor.dart';
import 'DioMethod.dart';
import 'package:dio/adapter.dart'; // 新增导入



class DioUtil{

  ///链接超时时间
  static const CONNECT_TIMEOUT = 5*1000;

  ///响应超时时间
  static const RECEIVE_TIMEOUT = 5*1000;

  ///请求的URL前缀
  static const BASE_URL = Settings.appServer;

  ///是否开启网络缓存，默认为false
  static const CACHE_ENABLE = false;

  ///最大缓存时间（秒）
  static int MAX_CACHE_AGE=7*24*60*60;

  ///最大缓存记录
  static int MAX_CACHE_COUNT = 100;

  //定义一个共用的取消令牌，可用于用户操作时token校验失败取消其他请求操作
  late final CancelToken cancelToken = CancelToken();
  Dio? _dio;
  static final DioUtil _instance = DioUtil._internal();


  // 启用忽略证书验证（开发环境使用）
  static const bool IGNORE_CERTIFICATE = true; // 设置为true开启忽略证书验证


  DioUtil._internal(){
    if(_dio==null){
      BaseOptions options = BaseOptions(
        // baseUrl: BASE_URL
        connectTimeout: CONNECT_TIMEOUT,
        receiveTimeout: RECEIVE_TIMEOUT,
      );

      _dio = Dio(options);

      // 添加忽略证书验证支持
      if (IGNORE_CERTIFICATE) {
        ignoreSSLCertificate();
      }

      //添加拦截器
      _dio?.interceptors.add(DioInterceptor());

      //是否开启日志
      // _dio?.interceptors.add(LogInterceptor(responseBody: true));


    }

  }

  /// 新增：配置忽略证书验证
  void ignoreSSLCertificate() {
    if (_dio == null) return;

    (_dio!.httpClientAdapter as DefaultHttpClientAdapter).onHttpClientCreate =
        (HttpClient client) {
      client.badCertificateCallback =
          (X509Certificate cert, String host, int port) => true;
      return client;
    };
  }

  /// 新增：设置启用/禁用忽略证书验证
  void setIgnoreCertificate(bool enable) {
    if (enable) {
      ignoreSSLCertificate();
    } else {
      // 恢复默认设置
      (_dio!.httpClientAdapter as DefaultHttpClientAdapter).onHttpClientCreate = null;
    }
  }

  static DioUtil getInstance(){
    return _instance;
  }

  ///文件下载
  Future<T> download<T>(String urlPath,savePath,{
    String? systemNo,
    DioMethod method = DioMethod.post,
    Map<String,dynamic> ?params,
    data,
    CancelToken? cancelToken,
    Options? options,
    ProgressCallback? onReceiveProgress,
  })async{
    const methodValues={
      DioMethod.get:'get',
      DioMethod.post:'post',
      DioMethod.delete:'delete',
      DioMethod.head:'head',
      DioMethod.patch:'patch',
      DioMethod.put:'put'
    };
    options??=Options(method: methodValues[method]);
    systemNo??=Settings.systemNo;
    if(options.extra==null){
      options.extra = {"systemNo":systemNo};
    }else{
      options.extra!["systemNo"] = systemNo;
    }
    try{
      Response? response = await _dio?.download(
        urlPath,
        savePath,
        data:data??{},
        queryParameters: params,
        cancelToken: cancelToken??cancelToken,
        options: options,
        onReceiveProgress:onReceiveProgress
      );
      return response?.data;
    }catch(e){
      rethrow;
    }
  }

  //取消
  cancel(){
    if(!cancelToken.isCancelled){
      cancelToken.cancel();
    }
  }

  Future<T> request<T>(String path,{
    String? systemNo,
    DioMethod method = DioMethod.post,
    Map<String,dynamic> ?params,
    data,
    CancelToken? cancelToken,
    Options? options,
    ProgressCallback? onSendProgress,
    ProgressCallback? onReceiveProgress,
  })async{
    const methodValues={
      DioMethod.get:'get',
      DioMethod.post:'post',
      DioMethod.delete:'delete',
      DioMethod.head:'head',
      DioMethod.patch:'patch',
      DioMethod.put:'put'
    };
    options??=Options(method: methodValues[method]);
    systemNo??=Settings.systemNo;
    if(options.extra==null){
      options.extra = {"systemNo":systemNo};
    }else{
      options.extra!["systemNo"] = systemNo;
    }
    try{
      Response? response = await _dio?.request(path,
        data:data??{},
        queryParameters: params,
        cancelToken: cancelToken??cancelToken,
        options: options,
        onSendProgress: onSendProgress,
        onReceiveProgress:onReceiveProgress
      );

      return response?.data;
    }catch(e){
      rethrow;
    }
  }

}